import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';

class JsCashPayment {
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  late InAppPurchase _inAppPurchase;
  late List<ProductDetails> _products;

  Function(String payload, String transactionId) onSuccess;
  Function(bool isCancel, String msg) onFailed;

  JsCashPayment({
    required this.onSuccess,
    required this.onFailed,
  }) {
    _inAppPurchase = InAppPurchase.instance;

    final Stream<List<PurchaseDetails>> purchaseUpdated = _inAppPurchase.purchaseStream;
    _subscription = purchaseUpdated.listen((purchaseDetailsList) {
      _listenToPurchaseUpdated(purchaseDetailsList);
    }, onDone: () {
      _subscription.cancel();
      onFailed(true, "Cancel");
    }, onError: (error) {
      error.printError();
      debugPrint("[Payment] ❌ Buy Failed !!!");
      onFailed(false, error.toString());
    });
  }

  void resumePurchase() {
    _inAppPurchase.restorePurchases();
  }

  /// 加载全部的商品
  void buyProduct(String productId) async {
    debugPrint("[Payment] 🍜 Shop id: $productId");

    List<String> outProducts = [productId];

    final bool available = await _inAppPurchase.isAvailable();
    if (!available) {
      debugPrint("[Payment] ❌ Unable to connect to the store");
      onFailed(false, "Unable to connect to the store");
      return;
    }

    //开始购买
    debugPrint("[Payment] ✅ Connected - Start querying all products");
    List<String> kIds = outProducts;

    final ProductDetailsResponse response = await _inAppPurchase.queryProductDetails(kIds.toSet());
    debugPrint("[Payment] ✅ Shop result: ${response.productDetails}");
    if (response.notFoundIDs.isNotEmpty) {
      debugPrint("[Payment] ❌ The specified item cannot be found");
      onFailed(false, "The specified product could not be found");
      return;
    }

    // 处理查询到的商品列表
    List<ProductDetails> products = response.productDetails;
    debugPrint("[Payment] ✅ products ==== ${products.length}");
    if (products.isNotEmpty) {
      //赋值内购商品集合
      _products = products;
    }

    //先恢复可重复购买
    // await _inAppPurchase. ();

    _startPurchase(productId);
  }

  // 调用此函数以启动购买过程
  void _startPurchase(String productId) async {
    debugPrint("[Payment] 🍜 Shop id: $productId");
    if (_products.isNotEmpty) {
      // ToastUtil.showToast("准备开始启动购买流程");
      try {
        ProductDetails productDetails = _getProduct(productId);

        debugPrint("[Payment] ✅ Start buy ~~~~ title=${productDetails.title}, desc=${productDetails.description}, price=${productDetails.price}, currencyCode=${productDetails.currencyCode}, currencySymbol=${productDetails.currencySymbol}");
        _inAppPurchase.buyConsumable(purchaseParam: PurchaseParam(productDetails: productDetails));
      } catch (e) {
        e.printError();
        debugPrint("[Payment] ❌ Buy failed !!!");
        onFailed(false, e.toString());
      }
    } else {
      debugPrint("[Payment] ❌ No products currently available");
      onFailed(false, "No products currently available");
    }
  }

  // 根据产品ID获取产品信息
  ProductDetails _getProduct(String productId) {
    return _products.firstWhere((product) => product.id == productId);
  }

  /// 内购的购买更新监听
  void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) async {
    for (PurchaseDetails purchase in purchaseDetailsList) {
      if (purchase.status == PurchaseStatus.pending) {
        // 等待支付完成
        _handlePending();
      } else if (purchase.status == PurchaseStatus.canceled) {
        // 取消支付
        _handleCancel(purchase);
      } else if (purchase.status == PurchaseStatus.error) {
        // 购买失败
        _handleError(purchase.error);
      } else if (purchase.status == PurchaseStatus.purchased || purchase.status == PurchaseStatus.restored) {
        //完成购买, 到服务器验证
        _checkApplePayInfo(purchase);
      }
    }
  }

  /// 购买失败
  void _handleError(IAPError? iapError) {
    onFailed(false, iapError?.message ?? "IAPError");
  }

  /// 等待支付
  void _handlePending() {
    debugPrint("[Payment] ⏰ Waiting ...");
  }

  /// 取消支付
  void _handleCancel(PurchaseDetails purchase) {
    _inAppPurchase.completePurchase(purchase);
    onFailed(true, "[Payment] 😜 Cancel");
  }

  /// Apple支付成功的校验
  void _checkApplePayInfo(PurchaseDetails detail) async {
    _inAppPurchase.completePurchase(detail);

    String payload = detail.verificationData.serverVerificationData;
    String transactionId = detail.purchaseID ?? "";

    debugPrint("[Payment] ✅ Payment success ~~~");
    onSuccess(payload, transactionId);
  }

  void onClose() {
    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition = _inAppPurchase.getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      iosPlatformAddition.setDelegate(null);
    }
    _subscription.cancel();
  }
}
